package thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;

import org.junit.Test;

/**
 * 多线程操作哈希映射演示
 * @author fidel
 */
public class HashMapMultiThreadsDemo {
    @Test
    public void test() throws Exception {
        HashMap<Long, Object> hashMap = new HashMap<>();
        ConcurrentHashMap<Long, Object> concurrentHashMap = new ConcurrentHashMap<>();
        // Callable接口类似于Runnable，但后者不会返回结果也无法抛出经过检查的异常
        List<Map<Long, Object>> list = new Callable<>() {
            @Override
            public List<Map<Long, Object>> call() throws Exception {
                // 创建10万个线程，分别向指定哈希映射放入键值对
                for (int i = 0; i < 100000; i++) {
                    new Thread() {
                        @Override
                        public void run() {
                            hashMap.put(System.nanoTime(), new Object());
                            concurrentHashMap.put(System.nanoTime(), new Object());
                        }
                    }.start();
                }
                List<Map<Long, Object>> set = new ArrayList<>();
                set.add(hashMap);
                set.add(concurrentHashMap);
                return set;
            }
        }.call();
        System.out.println(list.get(0).size());
        System.out.println(list.get(1).size());
    }
}
